package com.sanpu.kxe.business.trade.presenter;

import android.content.Intent;
import android.provider.ContactsContract;

import com.sanpu.kxe.business.trade.bean.RechargeDetailOutput;
import com.sanpu.kxe.business.trade.contract.ChargerTelFeeContract;
import com.sanpu.kxe.business.trade.model.TradeModel;
import com.sanpu.kxe.business.trade.provider.TradeOpenProvider;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.utils.IntentTool;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：话费流量充值
 * Created by 薛勇军 on 2019/3/15.
 */

public class ChargerTelFeePresenter implements ChargerTelFeeContract.Presenter {

    private ChargerTelFeeContract.View mView;

    private CompositeSubscription mSubscription;

    public ChargerTelFeePresenter(ChargerTelFeeContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void pickContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        IntentTool.startActivityForResult(mView.getContext(), intent, CommonConfig.REQUESTCODE_PICK_CONTACT);
    }

    @Override
    public void getRechargeDetail(final String phoneNumber) {
        mView.showLoadingDialog(true);
        Subscription subscription = TradeModel.getInstance().getRechargeDetail(phoneNumber)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RechargeDetailOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showDataView(null, phoneNumber);
                    }

                    @Override
                    public void onNext(RechargeDetailOutput rechargeDetailOutput) {
                        mView.showDataView(rechargeDetailOutput, phoneNumber);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void setupPay(String phoneNumber, RechargeDetailOutput.AmountPackage callcharge,
                         RechargeDetailOutput.PointPackage integral) {
        TradeOpenProvider.getInstance().openChargerTelSetupPayActivity(mView.getContext(),
                phoneNumber, callcharge, integral);
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
